package com.triones.yjj.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.system.service.ISysDictDataService;
import com.triones.biz.infra.controller.enums.SceneEnum;
import com.triones.biz.infra.entity.file.vo.FileVO;
import com.triones.biz.infra.service.file.FileService;
import com.triones.framework.common.util.weixin.WeixinUtil;
import com.triones.yjj.entity.MemberActivityRelateDO;
import com.triones.yjj.entity.bo.*;
import com.triones.yjj.entity.vo.*;
import com.triones.yjj.service.*;
import com.triones.yjj.service.payment.PaymentManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小程序api
 *
 * @Author: triones
 */
@SaIgnore
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/wx/member")
public class YjjApiController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final ISysDictDataService dictDataService;

    private final ComplainService complainService;

    private final FileService fileService;

    private final WeChatManager weChatManager;

    private final ActivityService activityService;

    private final GroupPurchaseGoodsItemService goodsItemService;

    private final MemberService memberService;

    private final OrderService orderService;

    private final StaffService staffService;

    private final PaymentManager paymentManager;

    private final MemberGroupPurchaseService memberGroupPurchaseService;

    private final GroupPurchaseGoodsService groupPurchaseGoodsService;

    private final GroupPurchaseGoodsItemService groupPurchaseGoodsItemService;

    private final ShareService shareService;

    private final InviteRewardService inviteRewardService;

    private final ActivityPrizeService activityPrizeService;

    private final ShareRecordService shareRecordService;

    private final MemberBrowseService memberBrowseService;

    private final MemberActivityRelateService memberActivityRelateService;

    private final MemberDistributionRecordService memberDistributionRecordService;

    private final QrService qrService;

    /**
     * 授权注册
     *
     * @param code
     * @param userId
     * @return
     */
    @GetMapping("/mini/openid")
    public R<Map> getMiniOpenid(@NotBlank(message = "code不能为空") String code, @NotNull(message = "商家ID不能为空") Long userId) {
        return weChatManager.getMiniOpenid(code, userId);
    }

    /**
     * 授权注册
     *
     * @param code
     * @return
     */
    @GetMapping("/mini/getOpenid")
    public R<Map> getOpenid(@NotBlank(message = "code不能为空") String code) {
        return weChatManager.getOpenid(code);
    }

    @PostMapping("/mini/setInfo")
    public R<WxUserVO> setInfo(@Validated @RequestBody WeChatMiniUserInfoBO weChatMiniUserInfoBO) {
        return weChatManager.userInfo(weChatMiniUserInfoBO);
    }

    @PostMapping("/mini/bind/phone")
    public R<Map> miniBindPhone(@Validated @RequestBody WeChatMiniBindPhoneBO weChatMiniBindPhoneBO) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(weChatMiniBindPhoneBO.getToken());
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map map = weChatManager.miniBindPhone(weChatMiniBindPhoneBO, memberDetailVO);
        String bindPhone = map.get("bindPhone").toString();
        if ("success".equals(bindPhone)) {
            return R.ok("绑定成功", map);
        }
        return R.fail("绑定失败：" + map.get("reason"));
    }

    @PostMapping(value = "/uploadImg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, Object>> avatar(@RequestPart("imgFile") MultipartFile imgFile) {
        Map<String, Object> ajax = new HashMap<>();
        if (!imgFile.isEmpty()) {
            try {
                FileVO fileVo = fileService.upload(imgFile.getOriginalFilename(), null, IoUtil.readBytes(imgFile.getInputStream()), SceneEnum.COMPLAIN.getScene());
                ajax.put("imgUrl", fileVo.getUrl());
                return R.ok(ajax);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }

    /**
     * 投诉原因列表
     */
    @GetMapping("/listComplaintReason")
    public R<List<SysDictData>> getListComplaintReason() {
        SysDictData dictData = new SysDictData();
        dictData.setDictType("complaint_reason");
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return R.ok(list);
    }

    /**
     * 提交投诉
     *
     * @return
     */
    @PostMapping("/submitComplaint")
    public R<T> submitComplaint(@Validated @RequestBody ComplainParams complainParams) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(complainParams.getToken());
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        complainParams.setMemberId(memberDetailVO.getId());
        if (complainService.getComplainBySourceId(complainParams)) {
            return R.fail("提交投诉失败，该活动你已投诉！");
        }
        boolean result = complainService.save(complainParams);
        if (result) {
            return R.ok("投诉提交成功！");
        } else {
            return R.ok("投诉提交失败！");
        }
    }

    @GetMapping("/activity/{id}")
    public R<ActivityWxInfoVO> getActivityById(@NotNull(message = "活动id不能为空") @PathVariable Long id) {
        ActivityWxInfoVO activityVO = activityService.getActivityInfoById(id);

        //tr_share_record  tr_order 我的邀请
        //我的奖励
        if (ObjectUtil.isEmpty(activityVO)) {
            return R.fail("失败，未找到相关活动");
        }
        List<GroupPurchaseGoodsItemWxVO> listGoodsItem = goodsItemService.getListByGoodsId(activityVO.getGroupPurchaseGoodsId());
        activityVO.setGoodsItemList(listGoodsItem);
        //查询当前用户的团和团成员
        return R.ok("成功", activityVO);
    }

    /**
     * 顶部弹幕列表(订单表非未付款)
     *
     * @param activityId
     * @return
     */
    @GetMapping("/{activityId}/topScrollList")
    public R<List<ActivityOrderUserVO>> topScrollList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId) {
        List<ActivityOrderUserVO> listScroll = activityService.getActivityOrderUserList(activityId);
        return R.ok(listScroll);
    }

    /**
     * 围观区头像(浏览量、分享量、报名量)
     *
     * @param activityId
     * @return
     */
    @GetMapping("/{activityId}/activityCount")
    public R<ActivityCountBSAVO> activityCount(@NotNull(message = "活动id不能为空") @PathVariable Long activityId) {
        ActivityCountBSAVO activityCountBSATotal = activityService.getActivityCountBSATotal(activityId);
        return R.ok(activityCountBSATotal);
    }

    /**
     * 查询可参团列表
     *
     * @param activityId
     * @param pageQuery
     * @return
     */
    @GetMapping("/{activityId}/groupPurchaseList")
    public R<TableDataInfo<WxMemberGroupPurchaseVO>> selectPageList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, PageQuery pageQuery) {
        TableDataInfo<WxMemberGroupPurchaseVO> groupPurchaseList = memberGroupPurchaseService.selectPageList(activityId, pageQuery);
        return R.ok(groupPurchaseList);
    }

    /**
     * 邀请排行榜
     *
     * @param activityId
     * @param pageQuery
     * @return
     */
    @GetMapping("/{activityId}/shareSortList")
    public R<TableDataInfo<WxShareSortVO>> selectShareSortPageList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, PageQuery pageQuery) {
        TableDataInfo<WxShareSortVO> groupPurchaseList = shareService.selectShareSortPageList(activityId, pageQuery);
        return R.ok(groupPurchaseList);
    }

    /**
     * 邀请奖励
     *
     * @param activityId
     * @param pageQuery
     * @return
     */
    @GetMapping("/{activityId}/inviteRewardList")
    public R<TableDataInfo<WxInviteRewardVO>> selectInviteRewardList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, PageQuery pageQuery) {
        TableDataInfo<WxInviteRewardVO> inviteRewardList = inviteRewardService.selectPageList(activityId, pageQuery);
        return R.ok(inviteRewardList);
    }

    /**
     * 底部购买记录(订单列表)
     *
     * @param activityId
     * @param pageQuery
     * @return
     */
    @GetMapping("/{activityId}/payOrderList")
    public R<TableDataInfo<ActivityOrderUserVO>> payOrderList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, PageQuery pageQuery) {
        TableDataInfo<ActivityOrderUserVO> activityOrder = orderService.getActivityPayOrderList(activityId, pageQuery);

        return R.ok(activityOrder);
    }

    /**
     * 用户登录
     *
     * @param activityId
     * @param openId
     * @return
     */
    @PostMapping("/login/{activityId}")
    public R<WxMemberVO> login(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, String openId) {
        ActivityWxInfoVO activityVO = activityService.getActivityInfoById(activityId);
        if (ObjectUtil.isNotEmpty(activityVO)) {
            WxMemberVO wxMemberVO = weChatManager.memberWxLogin(activityVO, openId);
            if (ObjectUtil.isNotEmpty(wxMemberVO)) {
                return R.ok("登录成功", wxMemberVO);
            } else {
                return R.fail("登录失败");
            }
        }
        return R.fail("登录失败,活动不存在");
    }

    /**
     * 我的凭证（订单）
     *
     * @param token
     * @return
     */
    @GetMapping("/orderVoucher")
    public R<WxMemberOrderVoucherVO> getMemberOrderVoucher(String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        WxMemberOrderVoucherVO wxMemberOrderVoucherVO = orderService.getMemberOrderVoucher(memberDetailVO.getId());
        return R.ok(wxMemberOrderVoucherVO);
    }

    /**
     * 活动最新订单记录 （下单付款的 STATUS IN (2, 5)）
     *
     * @param activityId
     * @return
     */
    @GetMapping("/{activityId}/orderList")
    public R<List<ActivityOrderUserVO>> getActivityOrderMemberList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId) {
        List<ActivityOrderUserVO> activityOrderMemberList = orderService.getActivityOrderMemberList(activityId);
        return R.ok(activityOrderMemberList);
    }

    /**
     * 是否是员工
     *
     * @param token
     * @return
     */
    @GetMapping("/getWxStaff")
    public R<WxUserStaffVO> getWxUserStaffInfo(String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        WxUserStaffVO wxUserStaffVO = new WxUserStaffVO();
        wxUserStaffVO.setHasStaff(false);
        StaffVO staffVO = staffService.getDetailByWxId(memberDetailVO.getWxUserId(), memberDetailVO.getUserId());
        if (ObjectUtil.isNotEmpty(staffVO)) {
            wxUserStaffVO.setHasStaff(true);
            wxUserStaffVO.setStaffVO(staffVO);
        }
        return R.ok(wxUserStaffVO);
    }

    /**
     * 活动所有订单记录
     *
     * @param activityId
     * @return
     */
    @GetMapping("/{activityId}/allOrderList")
    public R<List<ActivityOrderUserVO>> allOrderList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId) {
        List<ActivityOrderUserVO> activityOrderMemberList = orderService.getActivityAllOrderList(activityId);
        return R.ok(activityOrderMemberList);
    }

    @PostMapping("/createOrder")
    public R<Map> createOrder(WxOrderParam param) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(param.getToken());
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        //查询活动
        ActivityVO activityVO = activityService.selectVoById(param.getActivityId());
        if (ObjectUtil.isEmpty(activityVO)) {
            return R.fail("活动不存在！");
        }
        //校验活动时间
        String nowDate = DateUtil.getDateTimeString();
        if(DateUtil.comparaDateTime(activityVO.getStartTime(),nowDate)||activityVO.getState().intValue()==0){
            return R.fail("活动还未开始，敬请期待！");
        }
        if(DateUtil.comparaDateTime(nowDate,activityVO.getEndTime())||activityVO.getState().intValue()==2){
            return R.fail("活动已结束，谢谢参与！");
        }
        //查询商品
        GroupPurchaseGoodsVO groupPurchaseGoodsVO = groupPurchaseGoodsService.getInfoByGoodsId(activityVO.getGroupPurchaseGoodsId());
        if (ObjectUtil.isEmpty(groupPurchaseGoodsVO)) {
            return R.fail("商品不存在！");
        }
        param.setGroupPurchaseGoodsId(groupPurchaseGoodsVO.getId());
        //是否已下单
        Map<String, Object> enrollMmap = orderService.activityIsEnroll(memberDetailVO, param.getActivityId());
        boolean isEnroll = (boolean) enrollMmap.get("isEnroll");
        if(isEnroll){
           return R.fail("已参加过该活动，不能重复参加！");
        }

        boolean isCreateGroup = false;

        if ("0".equals(param.getOptionalIdentity())) {
            isCreateGroup = true;
            param.setOptionalIdentity(null);
        }

        int number = 1;
        //查询拼团
        if (param.getGroupPurchaseId().intValue() == -1) {
            isCreateGroup = true;
        } else {
            MemberGroupPurchaseVO memberGroupPurchaseVO = memberGroupPurchaseService.selectVoById(param.getGroupPurchaseId());
            if (ObjectUtil.isEmpty(memberGroupPurchaseVO)) {
                return R.fail("拼团不存在！");
            }
            if (memberGroupPurchaseVO.getStatus().intValue() == 3) {
                //已满团，重新开团
                isCreateGroup = true;
            } else if (memberGroupPurchaseVO.getStatus().intValue() == -1) {
                //团已失效，重新开团（2024-09-14 改）
                isCreateGroup = true;
            } else{
                if(isCreateGroup){
                    isCreateGroup = false;
                }
            }
            number = memberGroupPurchaseVO.getMaxPersonnelNumber();
        }
        if(isCreateGroup){
            number = 1;
        }
        GroupPurchaseGoodsItemVO groupPurchaseGoodsItemVO = groupPurchaseGoodsItemService.getGroupPurchaseGoodsItemInfo(groupPurchaseGoodsVO.getId(), number);
        if (ObjectUtil.isEmpty(groupPurchaseGoodsItemVO)) {
            return R.fail("拼团商品不存在！");
        }
        //查询阶梯商品
        if (isCreateGroup) {
            //创建团
            MemberGroupPurchaseBO memberGroupPurchaseBO = new MemberGroupPurchaseBO();
            memberGroupPurchaseBO.setTeamName(param.getEnrollName());
            memberGroupPurchaseBO.setMemberId(memberDetailVO.getId());
            memberGroupPurchaseBO.setMemberWxUserId(memberDetailVO.getWxUserId());
            memberGroupPurchaseBO.setMaxPersonnelNumber(groupPurchaseGoodsItemVO.getConstituteNumber());
            memberGroupPurchaseBO.setNature(groupPurchaseGoodsVO.getNature());
            memberGroupPurchaseBO.setActivityId(param.getActivityId());
            memberGroupPurchaseBO.setGroupPurchaseGoodsId(groupPurchaseGoodsVO.getId());
            memberGroupPurchaseBO.setGroupPurchaseGoodsItemId(groupPurchaseGoodsItemVO.getId());
            memberGroupPurchaseBO.setUserId(activityVO.getUserId());
            long memberGroupPurchaseId = memberGroupPurchaseService.createMemberGroupPurchase(memberGroupPurchaseBO);
            param.setGroupPurchaseId(memberGroupPurchaseId);
        }
        param.setGroupPurchaseGoodsItemId(groupPurchaseGoodsItemVO.getId());
        param.setActualAmount(groupPurchaseGoodsVO.getPrice());
        param.setAmountTotal(groupPurchaseGoodsVO.getPrice());
        param.setOpenId(memberDetailVO.getOpenId());
        param.setMemberId(memberDetailVO.getId());
        param.setMemberWxUserId(memberDetailVO.getWxUserId());
        param.setActivityTitle(activityVO.getTitle());
        StaffVO staffVO = staffService.getDetailById(param.getPerformanceStaffId());
        if (ObjectUtil.isEmpty(staffVO)) {
//            return R.fail("员工不存在！");
            param.setStaffWxUserId(0l);
            param.setPerformanceStaffId(0l);
        }else{
            param.setStaffWxUserId(staffVO.getWxUserId());
        }

        param.setUserId(memberDetailVO.getUserId());
        Map map = paymentManager.createOrder(param);
        //增加浏览类型报名
        memberBrowseService.saveBrowse(param.getActivityId(), staffVO, memberDetailVO, "enroll");
        return R.ok(map);
    }

    /**
     * 支付成功通知
     *
     * @param request
     * @param response
     */
    @RequestMapping("/payNotice")
    public void payNotice(HttpServletRequest request, HttpServletResponse response) {

        try {
            SAXReader saxReadr = new SAXReader();
            saxReadr.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            Document document = saxReadr.read(request.getInputStream());
            Map<String, String> params = WeixinUtil.xmlToMap(document);
            logger.info("微信支付回调" + JSONUtil.toJsonStr(params));
            String resXml = paymentManager.onCallback(params);
            response.setHeader("Content-Type", "text/xml");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 活动邀请奖品列表
     *
     * @param activityId
     * @return
     */
    @GetMapping("/{activityId}/activityPrizeList")
    public R<List<WxActivityPrizeVO>> activityPrizeList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, @NotBlank(message = "token不能为空")String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        //查询用户邀请信息
        MemberActivityRelateDO memberActivityRelateDO = memberActivityRelateService.selectOne(memberDetailVO.getId(), activityId);
        int inviteNum = 0;
        if (ObjectUtil.isNotEmpty(memberActivityRelateDO)) {
            inviteNum = memberActivityRelateDO.getInviteTotal();
        }
        WxActivityPrizeListParams prizeListParams = new WxActivityPrizeListParams();
        prizeListParams.setActivityId(activityId);
        prizeListParams.setUserId(memberDetailVO.getUserId());
        prizeListParams.setInviteNum(inviteNum);
        List<WxActivityPrizeVO> activityPrizeList = activityPrizeService.getWxActivityPrizeList(prizeListParams);
        return R.ok(activityPrizeList);
    }

    /**
     * 活动奖品价值及用户分享人数
     *
     * @param activityId
     * @return
     */
    @GetMapping("/{activityId}/getActivityRewardAmount")
    public R<Map<String, Object>> getActivityRewardAmount(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, @NotBlank(message = "token不能为空")String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map<String, Object> map = new HashMap<>();
        Double activityRewardAmount = inviteRewardService.getActivityRewardAmount(activityId, memberDetailVO.getUserId());
        map.put("activityRewardAmount", activityRewardAmount);
        //用户当前邀请人数
        int shareUserNum = 0;
        MemberActivityRelateDO memberActivityRelateDO = memberActivityRelateService.selectOne(memberDetailVO.getId(), activityId);
        if (ObjectUtil.isNotEmpty(memberActivityRelateDO)) {
            shareUserNum = memberActivityRelateDO.getInviteTotal();
        }
        map.put("shareUserNum", shareUserNum);
        return R.ok(map);
    }

    /**
     * 分享
     *
     * @param activityId
     * @param token
     * @return
     */
    @PostMapping("/{activityId}/share")
    public R<Map<String, Object>> addShare(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, @NotBlank(message = "token不能为空")String token, @NotNull(message = "员工ID不能为空")Long staffId) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map<String, Object> map = new HashMap<>();
        Long shareId = shareService.saveShare(activityId,staffId, memberDetailVO);
        //增加浏览类型分享
        StaffVO staffVO = staffService.getDetailById(staffId);
        memberBrowseService.saveBrowse(activityId, staffVO, memberDetailVO, "share");
        map.put("shareId", shareId);
        return R.ok(map);
    }


    /**
     * 分享记录（点击分享链接后生成）
     *
     * @param wxShareParams
     * @return
     */
    @PostMapping("/addShareRecord")
    public R<Long> addShareRecord(@Valid WxShareParams wxShareParams) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(wxShareParams.getToken());
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        //分享记录ID
        Long shareRecord = shareService.saveShareRecord(wxShareParams, memberDetailVO);
        //更新 最新访问的活动
        memberService.uploadLatelyActivity(memberDetailVO.getId(), wxShareParams.getActivityId());
        // 更新或创建客户与活动的关联
        memberActivityRelateService.createMemberActivityRelate(memberDetailVO.getId(), wxShareParams.getActivityId());
        return R.ok(shareRecord);
    }

    /**
     * 分享信息(查看人数、报名人数)
     *
     * @param activityId
     * @param token
     * @return
     */
    @GetMapping("/{activityId}/shareInfo")
    public R<ShareVO> shareInfo(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map map = new HashMap();
        ShareVO shareVO = shareService.getMemberShareInfo(activityId, memberDetailVO.getId(), memberDetailVO.getUserId());
        return R.ok(shareVO);
    }

    /**
     * 邀请列表
     *
     * @param activityId
     * @param token
     * @param pageQuery
     * @return
     */
    @GetMapping("/{activityId}/shareInviteList")
    public R<TableDataInfo<WxInviteRecordListVO>> shareInviteList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, String token, PageQuery pageQuery) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        TableDataInfo<WxInviteRecordListVO> activityOrder = shareRecordService.shareInvitePageList(activityId, memberDetailVO.getUserId(), memberDetailVO.getId(), pageQuery);
        return R.ok(activityOrder);
    }

    //客户浏览表
    @PostMapping("/browseStart")
    public R<Map> browseStart(@Valid MemberBrowseStartParams params) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(params.getToken());
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map map = new HashMap();
        StaffVO staffVO = staffService.getDetailById(params.getInviteStaffId());
        if (ObjectUtil.isNotEmpty(staffVO)) {
            params.setStaffWxUserId(staffVO.getWxUserId());
        }
        Long id = memberBrowseService.browseStart(params, memberDetailVO);
        // 更新邀请人数
        memberActivityRelateService.updateMemberActivityInviteTotal("browse", memberDetailVO.getId(), params.getActivityId(), params.getShareId());
        map.put("memberBrowseRecordId", id);
        return R.ok(map);
    }

    @PostMapping("/browseEnd")
    public R<T> browseEnd(MemberBrowseEndParams params) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(params.getToken());
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        params.setBrowseType("access");//浏览类型（分享：share、访问：access、报名：enroll）
        return memberBrowseService.browseEnd(params, memberDetailVO);
    }

    /**
     * 待核销订单列表
     *
     * @param activityId
     * @param token
     * @return
     */
    @GetMapping("/{activityId}/verificationOrderList")
    public R<List<ActivityOrderUserVO>> verificationOrderList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        List<ActivityOrderUserVO> orderVOList = orderService.getVerificationOrderList(activityId, memberDetailVO.getId());
        return R.ok(orderVOList);
    }

    /**
     * 核销订单（客户自主核销）
     *
     * @param orderId
     * @param token
     * @param staffId
     * @return
     */
    @PostMapping("/autonomousOrderVerification")
    public R<T> verificationOrder(@NotNull(message = "订单id不能为空") Long orderId,
                                  @NotBlank(message = "token不能为空") String token,
                                  @NotNull(message = "员工id不能为空") Long staffId) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        return orderService.memberVerificationOrder(memberDetailVO, orderId, staffId);
    }

    /**
     * 礼品-自主核销(客户扫员工码)
     *
     * @param verificationCode
     * @param token
     * @return
     */
    @PostMapping("/rewardVerification")
    public R<T> verificationReward(@NotBlank(message = "核销码不能为空") String verificationCode, @NotBlank(message = "token不能为空") String token, @NotNull(message = "员工id不能为空") Long staffId) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        return inviteRewardService.memberVerificationReward(memberDetailVO, verificationCode, staffId);
    }
    //员工中心点活动，新增分享信息（分享次数+1）
    //员工自己购买，生成分享记录，分享+1，订单存分享ID
    //员工分享.....1海报2活动分享 链接带分享记录ID，第一次为0

    /**
     * 查询活动是否成功报名
     *
     * @param activityId
     * @return
     */
    @GetMapping("/isEnroll/{activityId}")
    public R<Map<String, Object>> activityIsEnroll(@NotNull(message = "活动id不能为空") @PathVariable Long activityId, @NotBlank(message = "token不能为空")String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        return R.ok(orderService.activityIsEnroll(memberDetailVO, activityId));
    }

    /**
     * 团信息列表
     *
     * @param groupPurchaseId
     * @param token
     * @return
     */
    @GetMapping("/getGroupPurchaseInfo")
    public R<Map> getGroupPurchaseInfo(@NotNull(message = "团id不能为空") Long groupPurchaseId, @NotBlank(message = "token不能为空")String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        return R.ok(memberGroupPurchaseService.getMemberGroupPurchaseAndItem(groupPurchaseId));
    }

    /**
     * 待核销礼品列表
     *
     * @param token
     * @return
     */
    @GetMapping("/getInviteRewardList")
    public R<List<WxMemberInviteRewardVO>> getInviteRewardList(@NotBlank(message = "token不能为空")String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        List<WxMemberInviteRewardVO> list = inviteRewardService.getMemberRewardList(memberDetailVO.getId(), memberDetailVO.getUserId());
        return R.ok(list);
    }


    /**
     * 客户活动参团信息
     *
     * @param token
     * @return
     */
    @GetMapping("/getMemberActivityGroupPurchaseInfo")
    public R<Map> getMemberActivityGroupPurchaseInfo(@NotNull(message = "活动id不能为空") Long activityId,@NotBlank(message = "token不能为空")String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        return R.ok(memberGroupPurchaseService.getMemberGroupPurchaseAndItemInfo(activityId, memberDetailVO.getId()));
    }

    /**
     * 二维码创建
     * @param qrValue
     * @return
     */
    @GetMapping("/qrCreate")
    public R<Map> qrCreate(@NotBlank(message = "二维码值不能为空") String qrValue) {
        Map map = new HashMap();
        String qrImg = qrService.qrCreate(qrValue);
        map.put("qrImg", qrImg);
        return R.ok(map);
    }

    @PostMapping("/mini/bindPhone")
    public R<Map> bindPhone(@NotBlank(message = "token不能为空")String token,@NotBlank(message = "code不能为空")String code) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        String phoneNumber = weChatManager.getPhoneNumber(code,memberDetailVO.getOpenId());
        Map map = weChatManager.bindPhone(memberDetailVO, phoneNumber,token);
        String bindPhone = map.get("bindPhone").toString();
        if ("success".equals(bindPhone)) {
            return R.ok("绑定成功", map);
        }
        return R.fail("绑定失败：" + map.get("reason"));
    }

    @PostMapping("/applyWithdraw")
    public R<T> applyWithdraw(@NotNull(message = "提现金额不能为空")Double amount, @NotBlank(message = "token不能为空") String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        memberService.applyWithdraw(memberDetailVO.getId(), amount,"MEMBER");
        return R.ok("提现申请成功！");
    }

    /**
     * 累计收益和余额
     *
     * @param token
     * @return
     */
    @GetMapping("/getAmount")
    public R<Map> getAmount(@NotBlank(message = "token不能为空") String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map map = new HashMap();
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal walletAmount = BigDecimal.ZERO;
         memberDetailVO = memberService.selectDetailById(memberDetailVO.getId());
        if (ObjectUtil.isNotEmpty(memberDetailVO)) {
            amount = memberDetailVO.getDistributionAmount();
            walletAmount = memberDetailVO.getWalletAmount();
        }
        map.put("totalAmount", amount);//累计收益
        //余额
        map.put("walletAmount", walletAmount);
        return R.ok("成功", map);
    }

    /**
     * 查询佣金明细-佣金收益
     *
     * @param token
     * @return
     */
    @GetMapping("/getDistributionRecordList")
    public R<TableDataInfo<WxMemberDistributionRecordVO>> getDistributionRecordList(@NotBlank(message = "token不能为空") String token, PageQuery pageQuery) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        TableDataInfo<WxMemberDistributionRecordVO> verificationOrder = memberDistributionRecordService.getList(memberDetailVO.getId(), pageQuery);
        return R.ok(verificationOrder);
    }

    @GetMapping("/{activityId}/getOneDistributionRecordList")
    public R<TableDataInfo<WxMemberDistributionRecordVO>> getOneDistributionRecordList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId,@NotBlank(message = "token不能为空") String token, PageQuery pageQuery) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        TableDataInfo<WxMemberDistributionRecordVO> verificationOrder = memberDistributionRecordService.getOneDistributionRecordList(memberDetailVO.getId(),activityId, pageQuery);
        return R.ok(verificationOrder);
    }

    @GetMapping("/{activityId}/getTwoDistributionRecordList")
    public R<TableDataInfo<WxMemberDistributionRecordVO>> getTwoDistributionRecordList(@NotNull(message = "活动id不能为空") @PathVariable Long activityId,@NotBlank(message = "token不能为空") String token, PageQuery pageQuery) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        TableDataInfo<WxMemberDistributionRecordVO> verificationOrder = memberDistributionRecordService.getTwoDistributionRecordList(memberDetailVO.getId(),activityId, pageQuery);
        return R.ok(verificationOrder);
    }
    @GetMapping("/{activityId}/getOneDistributionCount")
    public R<Map<String,Object>> getOneDistributionCount(@NotNull(message = "活动id不能为空") @PathVariable Long activityId,@NotBlank(message = "token不能为空") String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map<String,Object> map = memberDistributionRecordService.getDistributionCount(memberDetailVO.getId(),activityId, 1);
        return R.ok(map);
    }
    @GetMapping("/{activityId}/getTwoDistributionCount")
    public R<Map<String,Object>> getTwoDistributionCount(@NotNull(message = "活动id不能为空") @PathVariable Long activityId,@NotBlank(message = "token不能为空") String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        Map<String,Object> map = memberDistributionRecordService.getDistributionCount(memberDetailVO.getId(),activityId, 2);
        return R.ok(map);
    }

    @PostMapping("/getStaffQr")
    public R<Map<String,Object>> getStaffQr(@NotNull(message = "员工id不能为空") Long staffId, @NotBlank(message = "token不能为空") String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        StaffVO staffVO = staffService.getDetailById(staffId);
        if (ObjectUtil.isNotEmpty(staffVO)) {
            Map<String,Object> map = new HashMap<>();
            map.put("qr",staffVO.getWxQrCode());
            return R.ok("成功", map);
        }
        return R.fail("员工不存在");
    }

    @GetMapping("/{shareId}/shareDetail")
    public R<ShareVO> shareDetail(@NotNull(message = "分享id不能为空") @PathVariable Long shareId, String token) {
        MemberDetailVO memberDetailVO = weChatManager.getCacheMember(token);
        if (ObjectUtil.isEmpty(memberDetailVO)) {
            return R.fail(401, "登录失效！");
        }
        ShareVO shareVO = shareService.getMemberShareDetail(shareId);
        return R.ok(shareVO);
    }

    /**
     * 获取海报图片
     */
    @GetMapping("/getPoster/{activityId}/{memberId}")
    public R<Map> getPosterImg(@NotNull(message = "活动id不能为空") @PathVariable Long activityId,
                                              @NotNull(message = "用户id不能为空") @PathVariable Long memberId,@NotBlank(message = "二维码值不能为空") String qrValue) throws Exception{
        return R.ok(activityService.getPosterImg(activityId,memberId,qrValue));
    }

    /**
     * 获取小程序二维码图片并携带参数
     */
    @PostMapping("/getPoster")
    public R<Map> getPosterImg(@Validated @RequestBody PosterBO bo) throws Exception {
        return R.ok(qrService.getMiniCodeImg(bo));
    }

    /**
     * 获取小程序二维码携带参数
     */
    @GetMapping("/miniCodeScene/{uuid}")
    public R<Map> getMiniCodeScene(@NotBlank(message = "uuid不能为空") @PathVariable("uuid") String uuid) {
        return qrService.getMiniCodeScene(uuid);
    }

    /**
     * 获取商家名称信息
     * @param id
     * @return
     */
    @GetMapping("/store/{id}")
    public R<String> getStoreName(@NotNull(message = "商家id不能为空") @PathVariable Long id) {
        return R.ok(activityService.getStoreName(id));
    }
}

